var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var router = require('./router/router');
var path = require('path');
var app = express();
var multer = require('multer');
var news = require('./model/new');
var user = require('./model/user');
var comment = require('./model/comment')

var storage = multer.diskStorage({
    destination:function(req,file,cb){
        cb(null,'D:/android studio/android_server/public/images')
    },
    filename:function(req,file,cb){
        cb(null,Date.now()+"-"+file.originalname);
    }
});
var upload = multer({ storage: storage }).any();
//app.use(upload);
// 配置模板引擎和 body-parser 一定要在 app.use(router) 挂载路由之前
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
app.use('/public/images/',express.static(path.join(__dirname,'./public/images/')));
app.use(cors({
    origin: true,
    credentials: true,
}));
app.use(router);
app.post('/upload',upload,(req,res)=>{
    var arr = [];
    var str = ""
    for(var i=0;i<req.files.length;i++){
        var name = req.files[i].filename.split('.')[0];
        arr.push(name);
    }
    if(arr.length === 1){
        str = arr[0]
    }else{
        for(var i=0;i<arr.length-1;i++){
            str += arr[i]+"&";
            // if(i=arr.length-1){
            //     str += arr[i]
            // }
        }
        str += arr[arr.length-1];
    }
    //var newStr = str.replace(/\'/g, "");
    user.findOne({username:req.body.username},(err,data)=>{
        if(err){
            return res.json({statusCode:500,message:'后台出错了'});
        }else{
            if(data.length === 0){
                return res.json({statusCode:200,message:'未找到用户'});
            }else{
                var {avatar,nickname} = data;
                news.find({type:'推荐'},(err,datas)=>{
                    if(err){
                        return res.json({statusCode:200,message:'未找到用户'});
                    }else{
                        if(data.length === 0){
                            return res.json({statusCode:200,message:'未找到用户'});
                        }else{
                            var page = 0;
                           if(datas.length%10===0){
                                page = datas[datas.length-1].page+1;
                           }else{
                               page = datas[datas.length-1].page;
                           }
                           //console.log(page,str);
                           //console.log(avatar,nickname,req.body.username);
                           var add_News = new news({
                               author:nickname,
                               title:req.body.content,
                               type:'推荐',
                               time:getNowFormatDate(),
                               avatar:avatar,
                               content:req.body.content,
                               like:0,
                               comment:0,
                               favorite:0,
                               images:str,
                               newType:4,
                               page:page,
                               isDetele:0,
                               username:req.body.username
                           });
                           add_News.save((err,data)=>{
                               if(err){
                                    return res.json({statusCode:500,message:'后台出错了'});
                               }else{
                                   res.json({statusCode:200,data:data});
                               }
                           })
                        }
                    }
                })
            }
        }
    })
});
app.post('/updateAvatar',upload,(req,res)=>{
    var newAvatar = req.files[0].filename.split(".")[0];
    var {username} = req.body;
   news.updateMany({username:username},{avatar:newAvatar},{ multi: true },(err,data)=>{
       if(err){
            return res.json({statusCode:500,message:'后台出错了'});
       }else{
           user.updateOne({username:username},{avatar:newAvatar},(err,data)=>{
               if(err){
                return res.json({statusCode:500,message:'后台出错了'});
            }else{
                    comment.updateMany({username:username},{avatar:newAvatar},{ multi: true },(err,data)=>{
                        console.log(data);
                        if(err){
                            return res.json({statusCode:500,message:'后台出错了'});
                        }else{
                            return res.json({statusCode:200,data:data});
                        }
                    })
                    
                }
           })
       }
   })
})
function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
            + " " + date.getHours() + seperator2 + date.getMinutes()
            + seperator2 + date.getSeconds();
    return currentdate;
}

app.listen(3009,()=>{
    console.log('server is running port 3009');
})